import React, { useEffect, useState } from 'react';
import { connect, Dispatch } from 'umi';
import {
  dashboardGroupsItem,
  IDashboardItem,
  IndexDetailItem,
  PanelsItem,
  PanelsParentItem,
} from '@/pages/SelfQuery/type';
import { ConnectState, IResponse } from '@/models/connect';
import { DataNode } from 'rc-tree/lib/interface';
import { Button, Card, Divider, Dropdown, Empty, Input, Menu, message, Modal, Spin, Tree } from 'antd';
import {
  ApartmentOutlined,
  EditOutlined,
  EllipsisOutlined,
  ExclamationCircleOutlined,
  PlusCircleOutlined,
  PlusOutlined,
} from '@ant-design/icons';

import WidgetBoardList from '@/components/WidgetBoardList';
import Widget from '@/components/Widget';

import { debounce } from 'lodash';
import styles from './style.less';
import { ISheetItem } from '@/pages/Analysis/type';
import ModalBox from '@/components/ModalBox';
import GlobalControlConfig from '@/pages/Analysis/Board/components/Filters/config/FilterConfig';

const { confirm } = Modal;

const AddPanelModel = React.lazy(() => import('./components/AddPanelModel'));
const AddGroupModel = React.lazy(() => import('./components/AddGroupModel'));
const AddIndexModel = React.lazy(() => import('./components/AddIndexModel'));
const WidgetGroup = React.lazy(() => import('@/components/WidgetGroup'));

interface PanelProps {
  dispatch: Dispatch;
  panels: Array<PanelsItem>;
  panelsThemeList: Array<any>;
  panelsParentList: Array<PanelsParentItem>;
  dashboard: IDashboardItem;
  dashboarding?: boolean;
  indexDetail: IndexDetailItem;
}

const Board: React.FC<PanelProps> = (props) => {
  const {
    panels,
    panelsThemeList,
    panelsParentList,
    dashboard,
    dashboarding,
    indexDetail,
    dispatch,
  } = props;
  const [expandedKeys, setExpandedKeys] = useState<Array<string>>([]); // 展开指定的树节点
  const [searchValue, setSearchValue] = useState<string>(''); // 搜索关键词
  const [selectTreeKey, setSelectTreeKey]index.tsx = useState<string>(''); // 选中的看板 KEY
  const [panelsItem, setPanelsItem] = useState<PanelsItem | any>(null); // 当前展示看板信息
  const [filterTreeData, setFilterTreeData] = useState<Array<any>>([]); // 关键词过滤后的树形结构数据
  const [panelModalVisible, SetPanelModalVisible] = useState<boolean>(false); // 新建面板弹框
  const [groupingModalVisible, SetGroupingModalVisible] = useState<boolean>(false); // 新建分组弹框
  const [indexModalVisible, SetIndexModalVisible] = useState<boolean>(false); // 添加指标弹框
  const [currentEditingProject, setCurrentEditingProject] = useState<any>(); // 当前选中的项目
  const [currentEditingPanel, setCurrentEditingPanel] = useState<any>(); // 当前选中的看板
  const [grobalFilterModalVisible, setGrobalFilterModalVisible] = useState<boolean>(false); // 全局搜索弹框展示
  const readerDashboard: IDashboardItem = JSON.parse(JSON.stringify(dashboard)); // 复制看板详情数据 操作删除逻辑 减少请求次数
  useEffect(() => {
    dispatch({
      type: 'sheet/fetchSheetList',
      callback: (res: Array<ISheetItem>) => {
      },
    });
  }, []);
  console.log('panelsItem',panelsItem)

  // 获取原始展示的树形结构数据
  const treeData: Array<DataNode> = panelsParentList
    .map((value: PanelsParentItem) => {
      const {projectId} = value;
      const treeData: DataNode = { title: `<项目>${value.projectName}`, key: String(projectId) };
      let children: Array<DataNode> = [];

      panelsThemeList.forEach((item: PanelsItem) => {
        if (item.projectId === projectId) {
          const {dashboardPortalId} = item;
          const portalTree: DataNode = {
            title: `<主题>${item.dashboardPortalName}`,
            key: `${projectId}-${dashboardPortalId}`,
          }; // 父子级存在相同key, 采用添加父级id前缀方式解决
          let panelsChildren: Array<DataNode> = [];

          panels.forEach((v: PanelsItem) => {
            if (v.projectId === projectId && v.dashboardPortalId === dashboardPortalId) {
              const panelsTree: DataNode = {
                title: `<看板>${v.dashboardName}`,
                key: `${projectId}-${dashboardPortalId}-${v.dashboardId}`,
              };
              panelsChildren.push(panelsTree);
            }
          });

          if (panelsChildren.length) {
            portalTree.children = panelsChildren;
          }

          children.push(portalTree);
        }
      });
      if (children.length) {
        treeData.children = children;
      }
      return treeData;
    })
    .filter((v) => v.children);

  // 树形结构点击选中
  const selectTree = (key: string) => {
    if (selectTreeKey === key) {
      return;
    }
    // 假如是在查看详情模式，清除数据退出
    dispatch({
      type: 'widget/fetchIndexDetail',
      payload: {},
    });

    setSelectTreeKey(key);

    const projectId = key.split('-')[0];
    const dashboardPortalId = key.split('-')[1];
    const dashboardId = key.split('-')[2];
    // 获得点击的整个对象
    panels.forEach((v: PanelsItem) => {
      if (
        v.projectId === Number(projectId) &&
        v.dashboardPortalId === Number(dashboardPortalId) &&
        v.dashboardId === Number(dashboardId)
      ) {
        setPanelsItem(v);
        // 获取子标列表
        dispatch({
          type: 'panel/fetchDashboard',
          payload: { portalId: v.dashboardPortalId, dashboardId: v.dashboardId },
        });
      }
    });
  };
  const grobalFilterShow = (id: number) => {
    console.log('id',id)

    setCurrentEditingPanel(panels.find(v => v.dashboardId === id));
    setGrobalFilterModalVisible(true);
  };
  const onOpenGrobalFilter = () => {
    setGrobalFilterModalVisible(!grobalFilterModalVisible);
  };
  // 树形结构节点自定义
  const loop = (data: any) => {
    const menuProjectClicks: any[] = [
      // {
      //   key: 1, name: '新增主题', func: () => {
      //   }
      // },
      // {key: 2, name: '全局控制器', func: grobalFilterShow},
    ];
    return data.map((item: any) => {
      const { key, title, children } = item;
      const onProjectClick = (menuKey: any, id: number) => {
        const list = menuProjectClicks.filter(value => value.key === menuKey);
        list[0].func(id);
      };
      // 项目列表
      if (children && children.length && children[0].children) {
        return {
          title: (
            <span className='parent'>
              <b>{title}</b>
               <Dropdown
                 overlay={
                   <Menu onClick={(value) => onProjectClick(value.key, key)}>
                     {menuProjectClicks.map((v: any) => {
                       return (
                         <Menu.Item key={v.key}>
                           {v.name}
                         </Menu.Item>
                       );
                     })}
                   </Menu>
                 }
               >
             <EllipsisOutlined />
            </Dropdown>
            </span>
          ),
          key,
          children: loop(children),
        };
      }

      // 主题列表
      if (children && children.length && !children[0].children) {
        return {
          title: (
            <span className='parent'>
              <b>{title}</b>
               <Dropdown
                 overlay={
                   <Menu>
                     <Menu.Item>添加看板</Menu.Item>
                   </Menu>
                 }
               >
                <PlusCircleOutlined />
              </Dropdown>
            </span>
          ),
          key,
          children: loop(children),
        };
      }
      // 看板列表
      return {
        title: (
          <span className={selectTreeKey === item.key ? 'treeChildren active' : 'treeChildren'}>
            <b
              onClick={() => {
                selectTree(item.key);
              }}
            >
              {title}
            </b>
             <Dropdown
               overlay={
                 <Menu>
                   <Menu.Item
                     onClick={()=>{
                       console.log('item',item)
                       grobalFilterShow(item.key)
                     }}
                   >全局筛选</Menu.Item>
                   <Menu.Item>编辑</Menu.Item>
                   <Menu.Item>分享</Menu.Item>
                   <Menu.Item>发布</Menu.Item>
                   <Menu.Item>删除</Menu.Item>
                 </Menu>
               }
             >
              <EditOutlined />
            </Dropdown>
          </span>
        ),
        key: item.key,
      };
    });
  };
  // 获得搜索到的内容节点并展开
  const serach = debounce((value) => {
    setSearchValue(value);
    if (value) {
      treeData.map((item) => {
        if (item.children) {
          item.children = item.children.filter((v: any) => v.title.indexOf(value) > -1);
        }
        return item;
      });
      const filterArr = treeData.filter((v: any) => v.children.length);
      let expandedArr: Array<string> = [];
      filterArr.forEach((item: any) => {
        expandedArr.push(item.key);
      });
      setExpandedKeys(expandedArr);
      setFilterTreeData(filterArr);
    }
  }, 200);

  // 搜索框输入值变化
  const onSearchChange = (e: any) => {
    e.persist();
    serach(e.target.value);
  };

  // 每次点击展开层级时触发
  const onExpand = (expandedKeys: Array<any>) => {
    setExpandedKeys(expandedKeys);
  };

  // 看板删除指标
  const removeWidgets = (id: number) => {
    confirm({
      title: '确认要移除指标吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'board/deleteWidgets',
          payload: { relationId: id },
          callback: (res: IResponse) => {
            const { header } = res;
            if (header.code === 200) {
              message.success('移除指标成功');
              const newWidgets = dashboard.widgets.filter((v) => v.id !== id);
              // 重新赋值看板详情数据
              dispatch({
                type: 'panel/sevaDashboard',
                payload: {
                  ...dashboard,
                  ...{ widgets: newWidgets },
                },
              });
            } else {
              message.warning('移除指标失败');
            }
          },
        });
      },
    });
  };

  // 存在分组情况，获得分组数据
  if (readerDashboard.groups && readerDashboard.groups.length) {
    let widgetsStrList: Array<string> = []; // 收集所有被分组的指标
    readerDashboard.groups.forEach((item: dashboardGroupsItem) => {
      if (item.groupName !== '未分组') {
        const groupsWidgetsID = item.widgets.split(',');
        widgetsStrList = widgetsStrList.concat(groupsWidgetsID); // 收集所有被分组的指标
        item.WidgetsArr = readerDashboard.widgets.filter(
          (v) => groupsWidgetsID.indexOf(String(v.widgetId)) > -1,
        );
      }
    });

    // 获得未分组的指标
    const notGroupsWidgets = readerDashboard.widgets.filter(
      (v) => widgetsStrList.indexOf(String(v.widgetId)) === -1,
    );

    if (
      notGroupsWidgets.length > 0 &&
      JSON.stringify(readerDashboard.groups).indexOf('未分组') === -1
    ) {
      readerDashboard.groups.push({
        WidgetsArr: notGroupsWidgets,
        dashboardId: 0,
        groupName: '未分组',
        id: 0,
        isDelete: false,
        widgets: '',
      });
    }
  }

  useEffect(() => {
    // 假如是在查看详情模式，清除数据退出
    dispatch({
      type: 'widget/fetchIndexDetail',
      payload: {},
    });

    // 获取看板列表
    dispatch({
      type: 'panel/fetchPanels',
      callback: (res: Array<PanelsItem>) => {
        if (res.length > 0) {
          // 默认请求第一个子标列表
          const item = res[0];
          setPanelsItem(item);

          setSelectTreeKey(`${item.projectId}-${item.dashboardPortalId}-${item.dashboardId}`);
          dispatch({
            type: 'panel/fetchDashboard',
            payload: { portalId: item.dashboardPortalId, dashboardId: item.dashboardId },
            callback: () => {
              setExpandedKeys([
                String(item.projectId),
                `${item.projectId}-${item.dashboardPortalId}`,
              ]);
            },
          });
        }
      },
    });
  }, []);

  return (
    <div className={styles.board}>
      <ModalBox />
      <Card
        bordered={false}
        title={<Input placeholder='搜索看板' onChange={onSearchChange} allowClear />}
        className={styles.panel}
      >
        <Tree
          treeData={searchValue ? loop(filterTreeData) : loop(treeData)}
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          blockNode
        />

        {searchValue && filterTreeData.length === 0 && (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description='无搜索结果' />
        )}

        <div className={styles.add} onClick={() => SetPanelModalVisible(true)}>
          <PlusOutlined />
        </div>
      </Card>
      <div className={styles.panelWrap}>
        {indexDetail.dataRecord && indexDetail.configs ? (
          // 指标详情
          <div className={styles.panelList}>
            <Widget parentTitle={dashboard.name} />
          </div>
        ) : (
          //  指标列表
          <Card
            className={styles.panelList}
            bordered={false}
            title={<div className={styles.dashboardTitle}>{dashboard && dashboard.name}</div>}
            extra={
              <div>
                {/*<Button*/}
                {/*  type="primary"*/}
                {/*  onClick={() => SetIndexModalVisible(true)}*/}
                {/*  icon={<PlusCircleOutlined/>}*/}
                {/*>*/}
                {/*  添加全局过滤器*/}
                {/*</Button>*/}
                <Button
                  type='primary'
                  onClick={() => SetIndexModalVisible(true)}
                  icon={<PlusCircleOutlined />}
                >
                  添加指标
                </Button>

                <Divider type='vertical' />
                <Button
                  type='primary'
                  icon={<ApartmentOutlined />}
                  onClick={() => SetGroupingModalVisible(true)}
                  disabled={dashboard.widgets && dashboard.widgets.length === 0}
                >
                  创建分组
                </Button>
              </div>
            }
          >
            {dashboarding ? (
              <div className={styles.loading}>
                <Spin size='large' />
              </div>
            ) : readerDashboard.widgets && readerDashboard.widgets.length > 0 ? (
              readerDashboard.groups && readerDashboard.groups.length > 0 ? (
                <div className={styles.groupWrap}>
                  <React.Suspense fallback={null}>
                    <WidgetGroup
                      groups={readerDashboard.groups}
                      panelsItem={panelsItem}
                      removeWidgets={removeWidgets}
                    />
                  </React.Suspense>
                </div>
              ) : (
                <WidgetBoardList
                  widgets={readerDashboard.widgets}
                  manage={true}
                  removeWidgets={removeWidgets}
                />
              )
            ) : (
              <Empty />
            )}
          </Card>
        )}
      </div>
      {/* 新建面板弹框 */}
      {panelModalVisible && (
        <React.Suspense fallback={null}>
          <AddPanelModel visible={panelModalVisible} onCancel={() => SetPanelModalVisible(false)} />
        </React.Suspense>
      )}

      {/* 新建分组弹框 */}
      {groupingModalVisible && dashboard.widgets && panelsItem && (
        <React.Suspense fallback={null}>
          <AddGroupModel
            visible={groupingModalVisible}
            onCancel={() => SetGroupingModalVisible(false)}
            widgetsList={dashboard.widgets}
            panelsItem={panelsItem}
            groups={dashboard.groups}
          />
        </React.Suspense>
      )}

      {/* 添加指标弹框 */}
      {panelsItem && indexModalVisible && (
        <React.Suspense fallback={null}>
          <AddIndexModel
            visible={indexModalVisible}
            onCancel={() => SetIndexModalVisible(false)}
            panelsItem={panelsItem}
            widgetsList={dashboard.widgets}
          />
        </React.Suspense>
      )}
      {/*{currentEditingProject ?*/}
      {/*  [*/}
      {/*    <GrobalFilter*/}
      {/*      visible={grobalFilterModalVisible}*/}
      {/*      project={currentEditingProject}*/}
      {/*      onCanel={closeFieldConfig}*/}
      {/*    />*/}
      {/*  ] : null}*/}
      <GlobalControlConfig visible={grobalFilterModalVisible} onCancel={onOpenGrobalFilter}/>
    </div>
  );
};
export default connect(({ widget, panel, loading, sheet }: ConnectState) => ({
  sheet: sheet,
  panels: panel.panels,
  panelsThemeList: panel.panelsThemeList,
  panelsParentList: panel.panelsParentList,
  dashboard: panel.dashboard,
  indexDetail: widget.indexDetail,
  dashboarding: loading.effects['panel/fetchDashboard'],
}))(Board);
